<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptins" class="table-view">
      <template #form="{ form }">
        <XForm ref="form" :fieldList="fieldList" :options="formOption" :formData="form" :originOption="originOption" class="grid grid-cols-3 gap-x-3" v-if="formShow"> </XForm>
      </template>
      <template #toolbar_btns>
        <div class="w-[100%]">
          <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
            <el-tab-pane label="组织维度" name="department"></el-tab-pane>
            <el-tab-pane label="品类维度" name="category"></el-tab-pane>
          </el-tabs>
          <div class="w-[100%] flex gap-x-3 mt-[6px]">
            <div class="flex-1">
              <el-button @click="importHandleClick">
                <span class="flex items-center"> <svg-icon icon-class="import" class="mr-[4px]" /> 导出 x</span>
              </el-button>
            </div>
            <FieldSelectBtn :fieldSelectConfig="fieldSelectConfig" @submit="query" />
          </div>
        </div>
      </template>
    </VTable>
    <!-- 导出中心 -->
    <DerivedCenter ref="DerivedCenterRef"></DerivedCenter>
  </VPage>
</template>

<script setup lang="jsx">
import { onMounted, ref, toRefs } from "vue"
import { longTermInventoryAnalysis } from "@/api/salesInventory"
import { ElMessage, ElMessageBox } from "element-plus"
import XForm from "@/components/XForm/index.vue"
const tableRef = ref()
const formShow = ref(false)
import FieldSelectBtn from "@/views/salesInventory/components/FieldSelectBtn.vue"
const fieldSelectConfig = ref({
  save: "longInventoryAnalyse",
  columnsShow: [],
  columns: [],
})
// 导出中心
import DerivedCenter from "@/components/DerivedCenter"
const DerivedCenterRef = ref()
const importHandleClick = async (e) => {
  let condition = {}
  DerivedCenterRef.value.open({
    tag_name: "performance_indicators",
    condition,
  })
}
const activeName = ref("department")
const handleClick = () => {
  tableRef?.value?.resetForm()
  tableRef?.value.query()
}

// 查询
const query = () => {
  tableRef?.value.query()
}
// 获取下拉数据
import { getAloneEnum } from "@/utils/enumUtils"
onMounted(async () => {
  let oneKeys = ["wmsAttribute", "warehouse"]
  let optData = await getAloneEnum(oneKeys)
  oneKeys.forEach((key) => {
    originOption.value[key] = optData?.[key]
  })
  setTimeout(() => {
    formShow.value = true
  }, 100)
})

// 枚举 数据
const originOption = ref({})

const formOption = ref({ inline: true })
const publicStyle = { style: { width: "200px" } }
const fieldList = ref([
  {
    field: "warehouse_id",
    type: "select",
    originField: "warehouse",
    multiple: true,
    collapseTags: true,
    options: { placeholder: "仓库" },
    ...publicStyle,
    itemProps: { placement: "right" },
  },
  {
    field: "warehouse_attr",
    type: "select",
    originField: "wmsAttribute",
    multiple: true,
    collapseTags: true,
    options: { placeholder: "仓库属性" },
    ...publicStyle,
  },
  {
    field: "department_id",
    type: "cascaderNew",
    cascaderType: "department",
    placeholder: "组织维度",
    cascaderProps: {},
    ...publicStyle,
    // "popper-append-to-body": false,
    // teleported: false,
    // placement: "right-start",
  },
  {
    field: "category",
    type: "cascaderNew",
    cascaderType: "category",
    placeholder: "产品品类",
    ...publicStyle,
  },
  {
    field: "end_at",
    type: "dateTimeRangeNorm",
    itemProps: {
      type: "daterange",
      valueFormat: "YYYY-MM-DD",
    },
    style: { width: "300px" },
  },
  {
    field: "dimension",
    type: "radio",
    options: {
      data: [
        { label: "周维度", value: "1" },
        { label: "月维度", value: "2" },
      ],
    },
    change: (e) => {
      tableRef?.value?.$table.loadColumn([])
      nextTick(() => {
        query()
      })
    },
    ...publicStyle,
  },
  {
    field: "sku",
    placeholder: "SKU",
    type: "textarea",
    ...publicStyle,
  },
])
// 初始化时间
import { parseTime } from "@/utils/ruoyi"
const initDate = () => {
  const temp = new Date()
  temp.setTime(temp.getTime() - 3600 * 1000 * 24 * 30)
  return [new Date(temp.setHours(0, 0, 0, 0)), new Date(new Date().setHours(23, 59, 59, 0))].map((d) => parseTime(d, "{y}-{m}-{d}"))
}
// 列表配置
const tableOptins = reactive({
  formConfig: {
    data: {
      dimension: "1",
      end_at: initDate(),
    },
  },
  columnConfig: {
    resizable: true,
  },
  border: "outer",
  columns: [{ type: "seq", field: "seq", title: "序号", width: 60 }],
  // pagerConfig: false,
  proxyConfig: {
    ajax: {
      query: ({ page, form }) => {
        console.log("query")
        let params = {
          page: page.pageNum,
          page_size: page.pageSize,
          ...initForm(form),
        }

        return queryList(params)
      },
    },
  },
  treeConfig: {
    // transform: true,
    // rowField: "fffff",
    // parentField: "parentId",
    // iconOpen: "vxe-icon-square-minus",
    // iconClose: "vxe-icon-square-plus",
    // transform: true,
    // childrenField: "children",
    // children: "children",
    // expandAll: true,
    hasChildField: "hasChild",
    lazy: true,
    loadMethod: ({ row }) => {
      return returnRow(row.child)
    },
  },

  showFooter: true,
  footerMethod({ columns, data }) {
    return [
      columns.map((column, columnIndex) => {
        if (column.type == "seq") return ""
        if (column.field === totalKey.value) {
          return "合计"
        } else {
          return sumNum(data, column.field)
        }
      }),

      columns.map((column, columnIndex) => {
        if (column.type == "seq") return ""
        if (column.field === totalKey.value) {
          return "品牌类合计"
        } else {
          return ""
          // return sumNum(data, column.field)
        }
      }),
      columns.map((column, columnIndex) => {
        if (column.type == "seq") return ""
        if (column.field === totalKey.value) {
          return "贸易类合计"
        } else {
          return ""
          // return sumNum(data, column.field)
        }
      }),
    ]
  },
})
// 合计
const sumNum = (list, field) => {
  let count = 0
  let fields = field?.split(".")
  let getObjKeys = (data) => {
    return fields.reduce((pre, cur) => pre[cur], data)
  }
  list.forEach((item) => {
    count += Number(getObjKeys(item, fields) || 0)
  })
  return count
}
import { filterColumns } from "@/views/salesInventory/components/method.js"
const totalKey = ref("")
// 查询类型
const tabColumn = {
  department: { field: "department_name", title: "组织", minWidth: 200, treeNode: true },
  category: { field: "category_name", title: "产品品类", minWidth: 200, treeNode: true },
}

// 二级表头字段 平台库存变化
const inventoryChanges = {
  title: "库存变化",
  align: "center",
  children: [
    { title: "BOH", key: "boh", width: 80 },
    { title: "变化", key: "changes", width: 80 },
  ],
}
// 三级表头字段
const configColumns = [
  { title: "总金额", key: "total_amount", width: 100 },
  { title: "超90天金额", key: "amount_exceeding_90_days", width: 100 },
  { title: "超90天占比", key: "ratio_exceeding_90_days", width: 100 },
  { title: "总金额环比", key: "total_amount_mom", width: 100 },
  { title: "超90天环比", key: "amount_exceeding_90_days_mom", width: 100 },
  { title: "超120天金额", key: "amount_exceeding_120_days", width: 100 },
  { title: "超120天金额占比", key: "ratio_exceeding_120_days", width: 130 },
  { title: "超120天金额环比", key: "amount_exceeding_120_days_mom", width: 130 },
]

const queryList = async (params) => {
  let rps = await longTermInventoryAnalysis(params)
  console.time("数据组装耗时")
  let warehouseData = rps.data?.[0]?.warehouse_data.map((v) => [v.platform_id, v.platform_name])
  let settledConfigColumns = []
  // 表格数据格式重组
  let { date, res } = initTableData(params.dimension, rps)

  // 表头列 配置
  warehouseData.forEach(([key, title]) => {
    let data = { title: title, field: key, align: "center", children: [] }
    date.forEach((title) => {
      data.children.push({
        title: title,
        align: "center",
        children: configColumns.map((v) => ({
          ...v,
          field: `warehouse_data.${key}.month_data.${title}.${v.key}`,
          fieldShow: `warehouse_data.${key}.month_data.${v.key}`,
        })),
      })
    })
    // 平台库存变化
    let inventoryChange = JSON.parse(JSON.stringify(inventoryChanges))
    inventoryChange.children.forEach((item) => {
      item.field = `warehouse_data.${key}.inventory_changes.${item.key}`
      item.fieldShow = `warehouse_data.${key}.inventory_changes.${item.key}`
    })
    data.children = [...data.children, inventoryChange]

    settledConfigColumns.push(data)
  })
  let columnsData = [...tableOptins.columns, tabColumn[activeName.value], ...settledConfigColumns]
  fieldSelectConfig.value.columns = JSON.parse(JSON.stringify(columnsData)).map((v) => {
    if (v?.children) {
      v.children = [...v?.children?.[0]?.children, ...v?.children[v.children.length - 1].children]
    }
    return v
  })
  const { columns, key } = filterColumns(columnsData, fieldSelectConfig.value.columnsShow)
  totalKey.value = key

  tableRef?.value?.$table.loadColumn(columns)
  tableRef?.value.updateScroll()
  console.timeEnd("数据组装耗时")
  console.log(res)
  return res
}

const returnRow = async (child) => {
  let params = {
    ...initForm(tableRef?.value.getQueryForm()),
  }
  if (activeName.value == "department") {
    params.department_id = child
  } else {
    params.category = child
  }
  let rps = await longTermInventoryAnalysis(params)
  // 表格数据格式重组
  let { date, res } = initTableData(params.dimension, rps)
  return res.data
}
// 表格数据格式重组
const initTableData = (dimension = 1, res) => {
  // 判断是否存在子级
  res.data.forEach((item) => {
    item.child = item.department_child || item.category_child
    item.hasChild = !!item.child?.length
  })

  let date = []
  if (dimension == 1) {
    // 周维度
    res.data.forEach((item) => {
      item?.warehouse_data.forEach((items) => {
        items?.month_data?.forEach((row, i) => {
          items.month_data[i] = [...row?.week_data]
        })
        items.month_data = items.month_data.flat()
        // 周数据 Arr 转 Obj
        items.month_data = Object.fromEntries(items.month_data.map((v) => [v.week_date, { ...v }]))
        // 表头 日期
        date = Object.keys(items.month_data)
      })
      // 渠道数据 Arr 转 Obj
      item.warehouse_data = Object.fromEntries(item.warehouse_data.map((v) => [v.platform_id, { ...v }]))
    })
  } else {
    // 月维度
    res.data.forEach((item) => {
      item?.warehouse_data.forEach((items) => {
        items?.month_data?.forEach((row, i) => {
          delete row.week_data
        })
        // 月份数据 Arr 转 Obj
        items.month_data = Object.fromEntries(items.month_data.map((v) => [v.month, { ...v }]))
        // 表头 日期
        date = Object.keys(items.month_data)
      })
      // 渠道数据 Arr 转 Obj
      item.warehouse_data = Object.fromEntries(item.warehouse_data.map((v) => [v.platform_id, { ...v }]))
    })
  }
  return { date, res }
}

// 组装查询条件
const initForm = (form) => {
  form.end_at = {
    start: form.end_at?.[0] || "",
    end: form.end_at?.[1] || "",
  }
  let keys = ["sku"]
  keys.forEach((key) => {
    form[key] = form[key]?.split("\n")?.filter((v) => !!v.trim())
  })
  form.by = activeName.value
  return form
}
</script>
<style lang="scss" scoped>
:deep(.table-view) {
  .vxe-header--row:nth-child(2) {
    .vxe-header--column {
      // background: #eff3fe !important;
      background: var(--base-table-hover-bg-color);
    }
  }
  .vxe-body--column {
    // border-left: 1px solid #e6e7e9;
    // border-bottom: 1px solid #e6e7e9;
    border-left: 1px solid var(--base-link-color);
    border-bottom: 1px solid var(--base-link-color);
  }
  .vxe-header--column {
    // border-left: 1px solid #e6e7e9;
    // border-bottom: 1px solid #e6e7e9;
    border-left: 1px solid var(--base-link-color);
    border-bottom: 1px solid var(--base-link-color);
  }
  .vxe-footer--column {
    // border-left: 1px solid #e6e7e9;
    // border-bottom: 1px solid #e6e7e9;
    border-left: 1px solid var(--base-link-color);
    border-bottom: 1px solid var(--base-link-color);
  }

  .vxe-footer--row {
    // background: #eff3fe;
    background: var(--base-table-hover-bg-color);
  }
  .vxe-pager {
    display: none;
  }
}

.table-view {
  // background: #efefef;
  background: var(--base-color);
  :deep(.vx-table__form-content) {
    background-image: none;
  }
  :deep(.vx-table__content) {
    margin-top: 8px;
    // background: #fff;
    background: var(--base-color);
    border-radius: 6px;
    .vxe-buttons--wrapper {
      margin-right: -0.75rem;
    }
  }
}
</style>
